# coding: utf-8
from typing import Union, List

from PySide6.QtCore import Signal, Property
from PySide6.QtGui import Qt
from PySide6.QtWidgets import QVBoxLayout, QWidget, QHBoxLayout, QFileDialog
from qfluentwidgets import HeaderCardWidget, BodyLabel, TransparentToolButton, FluentIcon, TransparentPushButton
from qfluentwidgets.components.widgets.card_widget import CardSeparator


class FileCardItem(QWidget):
    deleted = Signal()

    def __init__(self, content: str, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self)
        self.horizontalLayout = QHBoxLayout()
        self.contentLabel = BodyLabel(content, self)
        self.deleteButton = TransparentToolButton(FluentIcon.CLOSE, self)
        self.separator = CardSeparator()
        self.verticalLayout.addWidget(self.contentLabel)

        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setContentsMargins(24, 10, 24, 10)
        self.horizontalLayout.addWidget(self.contentLabel)
        self.horizontalLayout.addWidget(self.deleteButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout.addWidget(self.separator)

        self.setSeparatorVisible(False)
        self.deleteButton.clicked.connect(self.deleted)

    def setSeparatorVisible(self, visible: bool):
        self.separator.setVisible(visible)

    def setContent(self, content: str):
        self.contentLabel.setText(content)

    def content(self) -> str:
        return self.contentLabel.text()

    def isSeparatorVisible(self):
        return self.separator.isVisible()


class FileListCardWidget(HeaderCardWidget):
    """ Group header card widget """

    def _postInit(self):
        super()._postInit()
        self.groupWidgets = []  # type: List[FileCardItem]
        self.contentList = []  # type: List[str]
        self.__filter = "全部文件 (*)"
        self.groupLayout = QVBoxLayout()
        self.selectButton = TransparentPushButton(FluentIcon.FOLDER_ADD, '添加文件', self)

        self.groupLayout.setSpacing(0)
        self.viewLayout.setContentsMargins(0, 0, 0, 0)
        self.groupLayout.setContentsMargins(0, 0, 0, 0)
        self.viewLayout.addLayout(self.groupLayout)

        self.headerLayout.addWidget(self.selectButton, 0, Qt.AlignRight)

        self.selectButton.clicked.connect(self.openFileDialog)
        self.adjustHeaderSeparator()

    def addGroup(self, content: str) -> FileCardItem:
        """ 卡片添加群组 """
        # 如果已经存在相同的组，则直接返回
        if content in self.contentList:
            return self.getGroup(content)

        group = FileCardItem(content, self)
        group.deleted.connect(lambda g=group: self.removeGroup(g))
        if self.groupWidgets:
            self.groupWidgets[-1].setSeparatorVisible(True)

        self.groupLayout.addWidget(group)
        self.contentList.append(content)
        self.groupWidgets.append(group)
        self.adjustHeaderSeparator()
        return group

    def removeGroup(self, group: FileCardItem):
        """ 卡片移除群组 """
        self.groupWidgets.remove(group)
        self.contentList.remove(group.content())
        self.groupLayout.removeWidget(group)
        group.deleteLater()
        self.adjustHeaderSeparator()

    def getGroup(self, content: str) -> Union[FileCardItem, None]:
        """ 卡片获取群组 """
        for group in self.groupWidgets:
            if group.content() == content:
                return group
        return None

    def count(self):
        return len(self.groupWidgets)

    def content(self):
        return [group.content() for group in self.groupWidgets]

    def openFileDialog(self):
        fileNames, _ = QFileDialog.getOpenFileNames(self, "选择文件", "", self.__filter,
                                                    options=QFileDialog.Option.DontUseCustomDirectoryIcons)
        for fileName in fileNames:
            self.addGroup(fileName)

    def adjustHeaderSeparator(self):
        if self.count() > 1:
            self.separator.setVisible(True)
        else:
            self.separator.setVisible(False)

    def setFilter(self, filter: str):
        self.__filter = filter

    def getFilter(self) -> str:
        return self.__filter

    filter = Property(str, getFilter, setFilter)
